package my.mall.admin.api.config;

import org.jetbrains.annotations.NotNull;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;

import java.time.*;

@Configuration
public class ParamConverterConfig {

    @Bean
    public Converter<String, LocalDateTime> localDateTimeConverter() {
        return new Converter<String, LocalDateTime>() {
            @Override
            public LocalDateTime convert(@NotNull String source) {
                Instant instant = Instant.ofEpochMilli(Long.parseLong(source));
                ZoneId zone = ZoneId.systemDefault();
                return LocalDateTime.ofInstant(instant, zone);
            }
        };
    }

    @Bean
    public Converter<String, LocalDate> localDateConverter() {
        return new Converter<String, LocalDate>() {
            @Override
            public LocalDate convert(@NotNull String source) {
                Instant instant = Instant.ofEpochMilli(Long.parseLong(source));
                ZoneId zone = ZoneId.systemDefault();
                return LocalDateTime.ofInstant(instant, zone).toLocalDate();
            }
        };
    }

    @Bean
    public Converter<String, LocalTime> localTimeConverter() {
        return new Converter<String, LocalTime>() {
            @Override
            public LocalTime convert(@NotNull String source) {
                Instant instant = Instant.ofEpochMilli(Long.parseLong(source));
                ZoneId zone = ZoneId.systemDefault();
                return LocalDateTime.ofInstant(instant, zone).toLocalTime();
            }
        };
    }
}
